<template>
  <div class="chat-wrapper">
    <!-- 顶部导航 -->
    <v-header ref="top" :title="chatObject.nickname"></v-header>

    <!-- 聊天区域 -->
    <scroll ref="scroll" :data="chatMsgList" :style="{height: mainHeight + 'px'}" style="overflow: hidden;">
      <ul class="message">
        <li v-for="msg in chatMsgList" :key="msg.id" :class="msg.type">
          <p class="time" v-if="msg.sendTimeStr !== ''"> <span>{{msg.sendTimeStr}}</span></p>
          <div class="main">
            <img v-lazy="msg.headUrl" class="avatar"/>
            <div class="text" v-html="msg.content"></div>
          </div>
        </li>
      </ul>
    </scroll>

    <!-- 底部输入框 -->
    <div class="bottom" ref="bottom">
      <div style="display: flex;">
        <div class="input" :style="{width: inputWidth + 'px'}">
          <textarea @keyup.enter="sendMessage" @focus="contentFocus" @blur="contentBlur" ref="textarea" v-model.trim="inputContent"></textarea>
          <i @click.stop="toggoleEmotion" class="fa fa-smile-o emoji" aria-hidden="true"></i>
        </div>
        <p class="send" @click="sendMessage">发送</p>
      </div>
      <!-- 表情 -->
      <emotion-grid v-show="showEmotion" @clickEmotion="clickEmotion" style="margin-top: 7px;"></emotion-grid>
    </div>
  </div>
</template>

<script>
import { localUser } from '@/assets/js/local'
import { isIOS, isIphoneX } from '@/assets/js/brower'
import axios from '@/api/axiosApi'

import VHeader from '@/components/v-header/v-header'
import Scroll from '@/components/scroll/scroll'
import EditableDiv from './editableDiv'
import EmotionGrid from './emotionGrid'
import { WechatEmotion as Emotion } from 'vux'
import { mapGetters } from 'vuex'

export default {
  data () {
    return {
      showEmotion: true,
      mainHeight: '',
      inputContent: '',
      softHeight: 0,   // 软键盘高度
      statusBarHeight: 24,   // 状态栏高度
      marginBottom: 0
    }
  },
  computed: {
    ...mapGetters([
      'JIM', 'chatObject', 'chatMsgList'
    ])
  },
  created () {
    this.inputWidth = window.innerWidth - 55 - 24 - 12
    if (isIphoneX()) {
      this.statusBarHeight = 44
      this.marginBottom = 34
      this.topHeight = 74
    } else {
      this.topHeight = 60
    }
    window._Native_heightChange = (height, visibleHeight) => {
      this.heightChange(height, visibleHeight)
    }
  },
  activated () {
    window._Native_heightChange = (height, visibleHeight) => {
      this.heightChange(height, visibleHeight)
    }
  },
  mounted() {
    this.autoTextarea(63, 0)
    setTimeout(() => {
      this.showEmotion = false
      this.$nextTick(() => {
        this.computedMainHeight(true)
      })
    }, 300)
  },
  components: {
    EditableDiv, EmotionGrid, VHeader, Scroll, Emotion
  },
  deactivated () {
    window._Native_heightChange = () => {}
  },
  destroyed () {
    if (this.heightTimer) {
      clearInterval(this.heightTimer)
    }
    this.$store.commit('SET_CHAT_OBJECT', {})
    window._Native_heightChange = () => {}
  },
  methods: {
    contentFocus (e) {
      if (isIOS()) {
        this.$refs.bottom.style.position = 'fixed'
      }
      const _self = this
      // 实时计算高度
      this.heightTimer = setInterval(() => {
        _self.computedMainHeight()
      }, 200)
    },
    heightChange (height, visibleHeight) {
      // 软键盘的收缩导致的高度变化。Android与IOS同样处理
      const scale = height / window.innerHeight // 1px在移动端所占像素点
      if ((height - visibleHeight) / scale <= this.statusBarHeight) {
        this.softHeight = 0
        this.$refs.top.$el.style.marginTop = '0'
        if (isIphoneX()) {
          this.marginBottom = 34
        }
      } else {
        this.marginBottom = 0
        if (isIOS()) {
          this.softHeight = (height - visibleHeight) / scale
        } else {
          this.softHeight = (height - visibleHeight) / scale - this.statusBarHeight
        }
        this.showEmotion = false
      }
      this.computedMainHeight()
    },
    contentBlur () {
      clearInterval(this.heightTimer)
    },
    computedMainHeight(first) {
      if (this.$refs.bottom) {
        this.$refs.bottom.style.position = 'relative'
        this.$refs.bottom.scrollIntoView()
        this.$refs.bottom.scrollIntoViewIfNeeded()
        this.$refs.bottom.style.bottom = '5px'
        this.mainHeight = window.innerHeight - this.topHeight - this.$refs.bottom.clientHeight - this.softHeight - this.marginBottom
      }
      let time = 300
      if (first) {
        time = 0
      }
      this.$nextTick(() => {
        if (this.$refs.scroll) {
          setTimeout(() => {
            if (this.$refs.scroll) {
              this.$refs.scroll.scroll.refresh()
              this.$refs.scroll.scroll.scrollTo(0, this.$refs.scroll.scroll.maxScrollY, time)
            }
          }, time)
        }
      })
    },
    sendMessage () {
      if (this.inputContent === '') {
        return
      }
      const value = this.inputContent
      this.inputContent = ''
      this.$refs.textarea.focus()
      const _self = this
      const JIM = this.$store.getters.JIM
      const user = localUser.get()
      JIM.sendSingleMsg({
        'target_username': _self.chatObject.id,
        'content': value
      }).onSuccess(function (data) {
        _self.$store.dispatch('sendMsg', {
          id: data.msg_id,
          type: 'to',
          username: _self.chatObject.id,
          nickname: user.nickname,
          headUrl: user.headUrl,
          content: value,
          contentType: 0,
          sendTime: data.ctime_ms
        })
        axios.post(_self, '/v1/pushAlias', {
          userId: _self.chatObject.id,
          content: `${localUser.get('nickname')}: ${value}`,
          linkUrl: `/user/friends`,
          messageType: 1,
          targetUrl: '/user'
        })
      }).onFail(function (data) {
        _self.$vux.toast.text('发送失败', 'middle')
      }).onTimeout(function (data) {
        _self.$vux.toast.text('发送超时', 'middle')
      })
    },
    toggoleEmotion () {
      this.showEmotion = !this.showEmotion
    },
    clickEmotion (emotion) {
      this.inputContent += emotion
    },
    autoTextarea (maxHeight, extra) {
      // textarea自适应高度
      const elem = this.$refs.textarea
      extra = extra || 0
      const isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window
      const isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera')
      const addEvent = function (type, callback) {
        elem.addEventListener ? elem.addEventListener(type, callback, false) : elem.attachEvent('on' + type, callback)
      }
      const getStyle = elem.currentStyle ? function (name) {
        var val = elem.currentStyle[name]
        if (name === 'height' && val.search(/px/i) !== 1) {
          var rect = elem.getBoundingClientRect()
          return rect.bottom - rect.top - parseFloat(getStyle('paddingTop')) - parseFloat(getStyle('paddingBottom')) + 'px'
        }
        return val
      } : function (name) {
        return getComputedStyle(elem, null)[name]
      }
      const minHeight = 26
      elem.style.resize = 'none'
      const change = function () {
        let height
        let padding = 0
        let style = elem.style
        if (elem._length === elem.value.length) return
        elem._length = elem.value.length
        if (!isFirefox && !isOpera) {
          padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'))
        }

        elem.style.height = minHeight + 'px'
        if (elem.scrollHeight > minHeight) {
          if (maxHeight && elem.scrollHeight > maxHeight) {
            height = maxHeight - padding
            style.overflowY = 'visible'
          } else {
            height = elem.scrollHeight - padding
            style.overflowY = 'hidden'
          };
          style.height = height + extra + 'px'
          elem.currHeight = parseInt(style.height)
        }
      }
      addEvent('propertychange', change)
      addEvent('input', change)
      addEvent('focus', change)
      change()
    }
  },
  watch: {
    chatMsgList (newVal, oldVal) {
      // 处理时间
      newVal.forEach((item, index) => {
        if (this.moment().diff(this.moment(item.sendTime), 'days') <= 1) {
          item.sendTimeStr = this.moment(item.sendTime).format('HH:mm')
        } else {
          item.sendTimeStr = this.moment(item.sendTime).format('YYYY-MM-DD HH:mm')
        }
        if (index > 0) {
          if (this.moment(item.sendTime).diff(this.moment(newVal[index - 1].sendTime), 'minutes') < 4) {
            item.sendTimeStr = ''
          }
        }
      })
    },
    showEmotion () {
      this.$nextTick(() => {
        this.computedMainHeight()
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'

.chat-wrapper {
  background-color: @color-background;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  .message {
    padding: 10px 15px;
    list-style: none;
    li {
      margin-bottom: 15px;
      .time {
        margin: 4px 0;
        text-align: center;
        span{
          display: inline-block;
          padding: 4px 18px;
          font-size: 13px;
          color: #fff;
          border-radius: 2px;
          background-color: #dcdcdc;
          line-height: 1;
        }
      }
      .avatar {
        float: left;
        width: 40px;
        height: 40px;
        margin: 0 10px 0 0;
        border-radius: 3px;
      }
      .text {
        display: inline-flex;
        position: relative;
        padding: 3px 10px;
        max-width: calc(100% - 100px);
        min-height: 30px;
        line-height: 1.8;
        font-size: 15px;
        text-align: left;
        word-break: break-all;
        background-color: #ffffff;
        border-radius: 4px;
        align-items: center;

        &:before {
          content: " ";
          position: absolute;
          top: 9px;
          right: 100%;
          border: 6px solid transparent;
          border-right-color: #ffffff;
        }
      }
    }
    .to {
      text-align: right;
      .avatar {
        float: right;
        margin: 0 0 0 10px;
      }
      .text {
        background-color: #b2e281;
        &:before {
          right: inherit;
          left: 100%;
          border-right-color: transparent;
          border-left-color: #b2e281;
        }
      }
    }
  }

  .bottom {
    position: fixed;
    bottom: -223px;
    left: 0;
    right: 0;
    padding: 5px 12px;
    background: #eee;
    border-top: 1px solid $color-border;
    background: #ffffff;

    .input {
      position: relative;
      border-radius: 3px;
      border: 1px solid $color-border;
      padding-top: 6px;
      padding-bottom: 6px;
      textarea {
        width: 100%; /*自动适应父布局宽度*/
        padding-left: 7px;
        padding-right: 40px;
        word-break: break-all;
        flex: 1;
        resize: none;
        border: none;
        box-sizing: border-box;
        outline: none;
        font-size: 16px;
        line-height: 1.3;
        display: block;
      }
    }

    .send {
      width: 62px;
      height: 36px;
      line-height: 36px;
      text-align: center;
      border-radius: 3px;
      background: $color-theme;
      color: #fff;
      font-size: 16px;
      margin-left: 12px;
      margin-top: 2px;
    }

    .emoji {
      position: absolute;
      top: 3px;
      right: 9px;
      font-size 26px;
      color: $color-border
    }
  }
}
</style>

